<template>
	<view class="page">
		<hx-navbar title=" " :fixed="true" bar-placeholder="hidden" transparent="hidden" :background-color="[74, 192, 255]" color="#ffffff"/>
		<canvas :style="{'margin-top':statusBarHeight+15+'px'}" class="share_canvas" canvas-id="share_canvas"></canvas>
		<view class="btns dis-flex flex-y-center">
			<view class="btn_view t-c">
				<image class="save_btn" :src="imgPrefix('/static/image/icon/save_btn.png')"></image>
				<text>分享微信好友</text>
				<button class="share-btn" open-type="share">分享</button>
			</view>
			<view @tap="saveImageToPhotosAlbum()" class="btn_view t-c">
				<image class="save_btn" :src="imgPrefix('/static/image/icon/save_btn.png')"></image>
				<text>保存到手机</text>
			</view>
		</view>
	</view>
</template>

<script>
const app = getApp();
import Painter from 'mp-painter';
import { statusBarHeight } from '@/static/mixins/statusBarHeight.js';
import API from '@/static/api/index.js';
export default {
	mixins: [statusBarHeight],
	data() {
		return {
			tempFilePath:'',
			img:'/static/image/share_bg.png',
			teacherInfo:{},
			toShare:false
		};
	},
	onLoad(option) {
		console.log("onload",option)
		if(option.hasOwnProperty('teacherInfo')){
			this.teacherInfo=JSON.parse(decodeURIComponent(option.teacherInfo))
			this.showLoading('图片生成中...')
		}
	},
	onShow() {
		if(!this.toShare){
		let {teacher_id,teaching_year,headeravatar,nickname,teacher_course,day,hour,course_count}=this.teacherInfo;
		let status = teacher_course!=''&&teacher_course!=null;
		console.log("status",status)
		app._log(status)
		let page = status?'pages/teacher_detail/index':'pages/teacher/login_identity/index';
		API.getPageCode(`id=${teacher_course.teacher_course_id}`,page).then(({code,data,msg})=>{
			app._log(code,data,msg)
			if(code==1){
				// onReady 中
				let painter = new Painter(uni.createCanvasContext('share_canvas'));
				let childArr = [
						{ type: 'image',left:0,top:0,width: 654, height: 1136, src: this.imgPrefix('/static/image/teacher/share_bg.png') },
						{type: 'rect',position: "absolute",top: 506,left:64,width: 96,height: 96,borderRadius:24,background:"#ffffff"},
						{type: "clip",position: "absolute",top: 508,left:66,path: {type: "rounded-rect",width: 92,height: 92,borderRadius: 24},
						content: {type: "image",width: 92,height: 92,borderRadius: 24,src: headeravatar||this.imgPrefix('/static/image/icon/default_avatar.png')}},
						{type: 'text-block',content: (status?teacher_course.grade.title+teacher_course.language.title+nickname:'请先去填写开课课程'),fontWeight: "bold", lineClamp: 1,position: "absolute",top: 513,left:176,width: 435,fontSize: 36,color:'#fff'},
						{type: 'text',content: '评分：',position: "absolute",top: 573,left:176,fontSize:24,color:'#fff'},
						
						{type: 'text',content: hour,position: "absolute",top: 746,left:64,fontSize:56,color:'#fff'},
						{type: 'text',content: '时',position: "absolute",top: 764,left:Number(64+(hour.toString().length*35)),fontSize:26,color:'#fff'},
						
						{type: 'text',content: course_count,position: "absolute",top: 746,left:278,fontSize:56,color:'#fff'},
						{type: 'text',content: '课',position: "absolute",top: 764,left:Number(278+(course_count.toString().length*35)),fontSize:26,color:'#fff'},
						
						
						{type: 'text',content: teaching_year,position: "absolute",top: 746,left:494,fontSize:56,color:'#fff'},
						{type: 'text',content: '年',position: "absolute",top: 764,left:Number(494+(teaching_year.toString().length*35)),fontSize:26,color:'#fff'},
						
						{type: 'text',content: '评分：',position: "absolute",top: 573,left:176,fontSize:24,color:'#fff'},
						{type: 'image',position: "absolute",top: 918,left:434,width: 132,height: 132,src: data} // 小程序码
					]
					let imgArr = []
					for(let i = 0;i<Math.ceil(status?teacher_course.score:5);i++){
						imgArr.push({ type: 'image',left:238+(i*32)+(i>1?(i-1)*2:0),top:565,position: "absolute",width: 32, height: 32, src: this.imgPrefix('/static/image/icon/comment_status_1.png') })
					}
				painter.draw({
					type: 'container',
					direction: "horizontal",
					top: 0,
					left: 0,
					children: childArr.concat(imgArr) // 追加星
				});
				setTimeout(()=>{
					uni.canvasToTempFilePath({
						canvasId: 'share_canvas',
						success:({tempFilePath})=>{
							app._log(tempFilePath)
							this.tempFilePath = tempFilePath;
						},
						fail: function(res) {
							app._log(res);
						}
					});
					this.hideLoading()
				},2000)
			}else{
				this.showToast(msg||'生成图片失败')
			}
		}).catch(err=>{
			app._log(err)
			this.showToast(err.msg||'生成图片失败')
		})
		}
	},
	methods:{
		  saveImageToPhotosAlbum() {
			let {tempFilePath}=this;
			if(tempFilePath==''){
				this.showToast('图片生成中，请稍后')
			}else{
				uni.getImageInfo({
					src:tempFilePath,
					success: (res) => {
						uni.saveImageToPhotosAlbum({
						  filePath: res.path,
						  success: function(data) {
							  app._log(data)
								uni.showModal({
								  title: '图片保存成功',
								  content: '图片成功保存到相册了，去发圈噻~',
								  showCancel: false,
								  confirmText: '好哒',
								  confirmColor: '#72B9C3'
								})
						  },
						  fail: function(err) {
							  app._log(err)
						    if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
						      uni.showModal({
						        title: '提示',
						        content: '需要获取权限才能保存到相册',
						        success(res) {
						          if (res.confirm) {
						            uni.openSetting({
						              success(settingdata) {
						                if (settingdata.authSetting['scope.writePhotosAlbum']) {
						                  uni.showToast({ title: '获取权限成功'})
						                  app._log('获取权限成功，给出再次点击图片保存到相册的提示。')
						                } else {
						                  uni.showModal({
						                    title: '提示',
						                    content: '没有权限，人家很难给你保存到相册',
						                    showCancel: false,
						                    confirmText: '好的',
						                    confirmColor: '#72B9C3',
						                    success: function(res) {}
						                  })
						                  app._log('获取权限失败，给出不给权限就无法正常使用的提示')
						                }
						              }
						            })
						          } else if (res.cancel) {
						            // app._log('用户点击取消')
						          }
						        }
						      })
						    }
						  }
						})
					}
				})
			}
		  }
	},
	onShareAppMessage(res) {
		if (res.from === 'button') {// 来自页面内分享按钮
			app._log(res.target)
		}
		this.toShare=true;
		let {teacherInfo} =this
		let {teacher_course} =teacherInfo
		return {
			title:teacher_course!=null?'教师详情':'可语小程序',
			imageUrl:this.imgPrefix('/static/image/share_cover.png'),
			path: teacher_course!=null?("/pages/teacher_detail/index?id=" + teacherInfo.teacher_course.teacher_course_id):"/pages/teacher/login_identity/index",
			complete:()=>{
				setTimeout(()=>{
					this.toShare=false;
				},500)
	　　　　　　// 转发结束之后的回调（转发成不成功都会执行）
	　　　　}
		}
	}
};
</script>
<style lang="scss">
.page {
	background-image: linear-gradient(315deg, #5b1bf5 0%, #8038ff 100%);
	padding-top: 24rpx;
	padding-bottom: calc(constant(safe-area-inset-bottom) + 84rpx);
	padding-bottom: calc(env(safe-area-inset-bottom) + 84rpx);
}
.share_canvas {
	width: 654rpx;
	height: 1118rpx;
	margin: 0 48rpx;
}

.btns{
	padding-top: 48rpx;
	justify-content: space-around;
	.btn_view{
		position: relative;
	}
}
.save_btn{
	width: 80rpx;
	height: 80rpx;
	
}
text{
	display: block;
	font-size: 24rpx;
	text-align: center;
	color: #fff;
}
</style>
